/// CRUD * 弹框-新增

<template>
  <ExModal :width="680" @ok="ok" @cancel="cancel">
    <!-- 表单 -->
    <ExForm v-bind="form.bind">
      <ARow :gutter="16">
        <!-- 表单项-站点名称 -->
        <ACol :span="12">
          <ExFormItem label="站点名称" name="siteName" :rule="rule().len(20)">
            <AInput />
          </ExFormItem>
        </ACol>
        <!-- 表单项-所属系统 -->
        <ACol :span="12">
          <ExFormItem
            label="所属系统"
            name="systemId"
            :rule="rule()"
            :readonly="params?.action === 'edit'"
            :view="findOption(OPTIONS_SYSTEM, detail?.systemId)?.label"
          >
            <ASelect :options="OPTIONS_SYSTEM" />
          </ExFormItem>
        </ACol>
      </ARow>
      <ARow :gutter="16">
        <!-- 表单项-所属分组 -->
        <ACol :span="12">
          <ExFormItem label="所属分组" name="groupId" :rule="rule()">
            <ASelect :options="OPTIONS_GROUP" />
          </ExFormItem>
        </ACol>
      </ARow>
      <!-- 表单项-备注 -->
      <ExFormItem label="备注" name="remarks">
        <ATextarea :maxlength="100" :rows="3" />
      </ExFormItem>
    </ExForm>
  </ExModal>
</template>

<script setup lang="ts">
import type { Loading, ModalProps } from '@expresso/plus'
import { findOption, rule } from '@expresso/plus'
import { OPTIONS_GROUP, OPTIONS_SYSTEM } from '../../helpers'
import { isSucceed } from '@/helpers'
import type { SiteDetail, SiteEntity } from '@/apis/system/project/Site'
import { apiAddSite, apiMergeSite, apiQuerySite } from '@/apis/system/project/Site'

//# 类型

type FormType = SiteEntity

type DetailType = SiteDetail

export type AddModalProps = ModalProps<{
  action: 'add' | 'edit'
  id?: number
}>

//# 属性

const $props = defineProps<AddModalProps>()

//# 成员

/** 加载器 */
const loading = inject<Loading>(ExDialogContextKeys.loading)!

/** 表单 */
const form = useForm<FormType>()

/** 详情 */
const detail = shallowRef<DetailType>()

//// 弹框 ////

/** 弹框-确定 */
const ok = async () => {
  try {
    await form.api?.validate()
    loading(async () => {
      switch ($props.params?.action) {
        case 'add': {
          const res = await apiAddSite(form.getData(true))
          if (isSucceed(res)) {
            $props.onOk?.()
          }
          break
        }
        case 'edit': {
          const res = await apiMergeSite(form.getData(true))
          if (isSucceed(res)) {
            $props.onOk?.()
          }
          break
        }
      }
    })
  } catch {}
}

/** 弹框-取消 */
const cancel = () => {
  $props.onCancel?.()
}

//# 周期

onMounted(() => {
  if ($props.params?.action === 'edit') {
    loading(async () => {
      form.setData((detail.value = await apiQuerySite($props.params!.id!)))
    })
  }
})
</script>

<style scoped></style>
